<template>
  <div class="container" :style="{ backgroundImage: `url(${background})` , backgroundSize: 'cover', backgroundRepeat: 'no-repeat',backgroundPosition: 'center'}">
    <header class="header">
      <h1>杂草检测系统图片预测模块</h1>
    </header>
    <main class="main">
      <section class="left-content">
        <!-- 左侧内容 -->
        <section class="left-content-up card">
          <!-- 左侧内容 -->
          <img v-if="selectedImage" :src="selectedImage" alt="Selected Image" class="selected-image">
        </section>
        <section class="left-content-down card">
          <!-- 左侧内容 -->
          <div class="upload-container">
            <label for="file-upload" class="upload-label">
              <i class="fas fa-upload"></i>
              上传图片
            </label>
            <input type="file" id="file-upload" accept="image/*" @change="handleFileUpload" class="upload-input">
          </div>
        </section>
      </section>
      <section class="middle-content">
        <!-- 中部内容 -->
        <section class="middle-content-up card"  ref="rightContentDown">
          <!-- 左侧内容 -->
        </section>
        <section class="middle-content-down card">
          <!-- 左侧内容 -->
        </section>
      </section>
      <section class="right-content">
        <!-- 右侧内容 -->
        <section class="right-content-up card">
          <!-- 左侧内容 -->
          <img v-if="predictedImage" :src="predictedImage" alt="Predicted Image" class="predicted-image">
        </section>
        <section class="right-content-down card">
          <!-- 左侧内容 -->
          <div class="predict-container">
            <button class="predict-button" @click="handlePredict">预测图片</button>
          </div>
        </section>
      </section>
    </main>
  </div>
</template>

<script>
import echarts from 'echarts'
import Background from '@/assets/detect/111.png'
export default {
  name: 'IndexPage',
  data() {
    return {
      background: Background,
      selectedImage: null,
      predictedImage: null,
      fps_y_data: Array.from({ length: 60 }, () => Math.floor(Math.random() * (130 - 70 + 1)) + 70),
      rightChartData: [
        { name: '早熟禾', value: 0, itemStyle: { color: '#FF5733' } },
        { name: '藜（灰菜）', value: 0, itemStyle: { color: '#29a13d' } },
        { name: '刺儿菜', value: 0, itemStyle: { color: '#5e75e5' } },
        { name: '玉米', value: 0, itemStyle: { color: '#c5ce42' } },
        { name: '莎草', value: 0, itemStyle: { color: '#7c1275' } },
        { name: '马齿苋', value: 0, itemStyle: { color: '#0e8883' } }
      ]
    };
  },
  mounted() {
    this.initRightChartDown();
  },
  methods: {
    initRightChartDown() {
      const chartDom = this.$refs.rightContentDown;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '图片中的目标数量'
        },
        tooltip: {},
        legend: {
          data: ['数量'],
          right: '10%', // 将图例放置在右上角
          top: '10%'
        },
        xAxis: {
          data: ["早熟禾", "藜（灰菜）", "刺儿菜", "玉米", "莎草", "马齿苋"],
          axisLabel: {
            interval: 0, // 强制显示所有标签
            rotate: 45, // 旋转标签以防止重叠
            margin: 10 // 标签与轴线的距离
          }
        },
        yAxis: {
          axisLabel: {
            formatter: function (value) {
              return Math.round(value);
            }
          }
        },
        series: [{
          name: '',
          type: 'bar',
          data: this.rightChartData,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}'
          }
        }]
      };
      myChart.setOption(option);
      this.rightChart = myChart; // 保存图表实例以便后续更新
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.selectedImage = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },
    handlePredict() {
      if (!this.selectedImage) {
        alert('请先上传图片');
        return;
      }

      // 将 base64 图片转换为 Blob
      const base64Image = this.selectedImage.split(',')[1];
      const byteCharacters = atob(base64Image);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'image/png' });

      const formData = new FormData();
      formData.append('file', blob, 'image.png');

      fetch('http://127.0.0.1:5000/picture_feed', {
        method: 'POST',
        body: formData
      })
        .then(() => {
          // 直接调用GET请求获取预测图片
          fetch('http://127.0.0.1:5000/get_detected_imgStr', {
            method: 'GET'
          })
            .then(response => response.json())
            .then(data => {
              console.log('Received detected objects:', data);
              this.predictedImage = `data:image/png;base64,${data}`;
              /* if (data && data.image) {
                // 将 Base64 字符串转换为 Data URL

              } else {
                console.error('Invalid response from server:', data);
                alert('获取预测图片失败，请重试');
              } */
            })
            .catch(error => {
              console.error('Error getting predicted image:', error);
              alert('获取预测图片失败，请重试');
            });
        })
        .then(() => {
          // 直接调用GET请求获取预测图片
          fetch('http://127.0.0.1:5000/get_detected_objects_a', {
            method: 'GET'
          })
            .then(response => response.json())
            .then(data => {
              console.log('Received detected objects:', data);
              // 提取并映射数据
              const newData = [
                { name: '早熟禾', value: data.bluegrass || 0, itemStyle: { color: '#FF5733' } },
                { name: '藜（灰菜）', value: data['chenopodium album'] || 0, itemStyle: { color: '#29a13d' } },
                { name: '刺儿菜', value: data['cirsium setosum'] || 0, itemStyle: { color: '#5e75e5' } },
                { name: '玉米', value: data.corn || 0, itemStyle: { color: '#c5ce42' } },
                { name: '莎草', value: data.sedge || 0, itemStyle: { color: '#7c1275' } },
                { name: '马齿苋', value: data['portulaca oleracea'] || 0, itemStyle: { color: '#0e8883' } }
              ];
              // 更新 rightChartData
              this.rightChartData = newData;
              // 更新图表数据
              this.rightChart.setOption({
                series: [{
                  data: this.rightChartData
                }]
              });
            })
            .catch(error => {
              console.error('Error getting predicted image:', error);
              alert('该图片未预测出目标。');
            });
        })
        .catch(error => {
          console.error('Error predicting image:', error);
          alert('预测失败，请重试');
        });
    }
  }
}
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.header {
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4CAF50;
  margin: 0;
  padding: 0;
}

.main {
  display: flex;
  height: 75%;
  margin: 0;
  padding: 0;
}

.middle-content {
  width: 30%;
  margin: 0;
  padding: 0;
}

.middle-content-down {
  flex: 1;
  background-color: #24794f; /* 蓝色 */
  margin: 0;
  height: 30%;
  box-sizing: border-box;
}

.middle-content-up {
  flex: 1;
  background-color: #c829e0; /* 蓝色 */
  margin: 0;
  height: 70%;
  box-sizing: border-box;
}

.middle-content img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图像比例并裁剪以填充容器 */
}

.left-content {
  width: 35%;
  margin: 0;
  padding: 0;
}

.left-content-down {
  flex: 1;
  background-color: #753cbb; /* 蓝色 */
  margin: 0;
  height: 15%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.left-content-up {
  flex: 1;
  background-color: #da5e83; /* 蓝色 */
  margin: 0;
  height: 70%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  width: 35%;
  margin: 0;
  padding: 0;
}

.right-content-down {
  flex: 1;
  background-color: #414252; /* 蓝色 */
  margin: 0;
  height: 15%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content-up {
  flex: 1;
  background-color: #a65f56; /* 蓝色 */
  margin: 0;
  height: 70%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.upload-label {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.upload-input {
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.selected-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; /* 保持图像比例并自适应容器 */

}

.card {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin: 5px;
  padding: 10px;
}


.predict-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.predict-button {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  border: none;
  width: 260px;
}

.predicted-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; /* 保持图像比例并自适应容器 */

}
</style>

